// 初始化学生数据
const STORAGE_KEY = 'data_student.csv';

// 从localStorage加载数据
function loadStudents() {
    const data = localStorage.getItem(STORAGE_KEY);
    if (data) {
        const lines = data.split('\n');
        const headers = lines[0].split(',');
        return lines.slice(1).map(line => {
            const values = line.split(',');
            return {
                id_student: values[0],
                name_student: values[1],
                area_student: values[2] || ''
            };
        });
    }
    return [];
}

// 保存数据到localStorage
function saveStudents(students) {
    const headers = ['学号', '姓名', '地址'];
    const csvLines = [
        headers.join(','),
        ...students.map(s => `${s.id_student},${s.name_student},${s.area_student}`)
    ];
    localStorage.setItem(STORAGE_KEY, csvLines.join('\n'));
}

// 导出CSV文件
function exportToCSV() {
    const students = loadStudents();
    const headers = ['学号', '姓名', '地址'];
    const csvContent = [
        headers.join(','),
        ...students.map(s => `${s.id_student},${s.name_student},${s.area_student}`)
    ].join('\n');
    
    const blob = new Blob(["\uFEFF" + csvContent], { type: 'text/csv;charset=utf-8;' });
    const url = URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.setAttribute('download', '学生信息.csv');
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
}

// 冒泡排序
function bubbleSort(students) {
    const n = students.length;
    for (let i = 0; i < n - 1; i++) {
        for (let j = 0; j < n - i - 1; j++) {
            if (students[j].id_student > students[j + 1].id_student) {
                [students[j], students[j + 1]] = [students[j + 1], students[j]];
            }
        }
    }
    return students;
}

// 更新表格显示
function updateTable() {
    const students = loadStudents();
    const sortedStudents = bubbleSort([...students]);
    
    let table = '<table><tr><th>学号</th><th>姓名</th><th>地址</th></tr>';
    sortedStudents.forEach(student => {
        table += `<tr>
            <td>${student.id_student}</td>
            <td>${student.name_student}</td>
            <td>${student.area_student}</td>
        </tr>`;
    });
    table += '</table>';
    
    document.getElementById('studentTable').innerHTML = table;
}

// 初始化页面
document.addEventListener('DOMContentLoaded', () => {
    // 1号表单提交 - 添加学生
    document.getElementById('inputForm').addEventListener('submit', (e) => {
        e.preventDefault();
        
        const id = document.getElementById('id_student').value.trim();
        const name = document.getElementById('name_student').value.trim();
        const area = document.getElementById('area_student').value.trim();
        
        if (!id || !name) {
            alert('学号和姓名不能为空');
            return;
        }
        
        const students = loadStudents();
        if (students.some(s => s.id_student === id)) {
            alert('该学号已存在');
            return;
        }
        
        students.push({ id_student: id, name_student: name, area_student: area });
        saveStudents(students);
        updateTable();
        
        // 清空表单
        e.target.reset();
        alert('添加成功');
    });

    // 修改按钮点击
    document.getElementById('modifyBtn').addEventListener('click', () => {
        document.getElementById('inputForm').style.display = 'none';
        document.getElementById('queryForm').style.display = 'block';
        document.getElementById('queryForm').dataset.action = 'modify';
    });

    // 删除按钮点击
    document.getElementById('deleteBtn').addEventListener('click', () => {
        document.getElementById('inputForm').style.display = 'none';
        document.getElementById('queryForm').style.display = 'block';
        document.getElementById('queryForm').dataset.action = 'delete';
    });

    // 取消查询
    document.getElementById('cancelQuery').addEventListener('click', () => {
        document.getElementById('inputForm').style.display = 'block';
        document.getElementById('queryForm').style.display = 'none';
    });

    // 2号表单提交 - 查询学号
    document.getElementById('queryForm').addEventListener('submit', (e) => {
        e.preventDefault();
        const queryId = document.getElementById('query_id').value.trim();
        const action = e.target.dataset.action;
        const students = loadStudents();
        const index = students.findIndex(s => s.id_student === queryId);
        
        if (index === -1) {
            alert('未找到该学号的学生信息');
            return;
        }
        
        if (action === 'delete') {
            students.splice(index, 1);
            saveStudents(students);
            updateTable();
            alert('删除成功');
        } else if (action === 'modify') {
            const student = students[index];
            document.getElementById('id_student').value = student.id_student;
            document.getElementById('name_student').value = student.name_student;
            document.getElementById('area_student').value = student.area_student;
            
            students.splice(index, 1);
            saveStudents(students);
        }
        
        document.getElementById('inputForm').style.display = 'block';
        document.getElementById('queryForm').style.display = 'none';
        e.target.reset();
    });

    // 初始加载
    updateTable();

    // 表格显示/隐藏切换
    document.getElementById('toggleTableBtn').addEventListener('click', () => {
        const table = document.getElementById('studentTable').querySelector('table');
        const btn = document.getElementById('toggleTableBtn');
        
        if (table.style.display === 'none' || !table.style.display) {
            table.style.display = 'table';
            btn.textContent = '隐藏';
        } else {
            table.style.display = 'none';
            btn.textContent = '显示';
        }
    });

    // 初始状态设置为隐藏
    document.getElementById('studentTable').querySelector('table').style.display = 'none';

    // 下载按钮点击事件
    document.getElementById('downloadBtn').addEventListener('click', exportToCSV);
});